<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
        <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table
       :data="roleList"
        stripe
        border
        style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter' ]" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag  closable>
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable>
                      {{item2.authName}}
                    </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" type="warning" closable :key="item3.id" @close='removeRightById(scope.row,item3.id)'>
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="80px"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editOpen(scope.row)">编辑</el-button>
            <el-button type="danger"  icon="el-icon-delete" size="mini" @click="deleteRole(scope.row)">删除</el-button>
            <el-tooltip  effect="dark" content="分配权限" placement="top" enterable>
              <el-button type="warning" icon="el-icon-star-off"  size="mini" @click="openSetRights(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色 -->
      <el-dialog
        title="提示"
        :visible.sync="addRoleDialogVisible"
        width="30%" @close='addRoleDialogClose'>
        <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAddRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色 -->
      <el-dialog
        title="提示"
        :visible.sync="editRoleDialogVisible"
        width="30%" @close='editRoleDialogClose'>
        <el-form :model="addForm" :rules="rules" ref="addForm" label-width="100px" >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="addForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="提示"
        :visible.sync="setRightsDialogVisible"
        width="50%" @close='setRightDialogClose'>
        <el-tree ref="rightTree" :data="rightsListTree" node-key="id" :props="treeProps" :default-checked-keys='defaultCheckKeys' show-checkbox default-expand-all></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { getRolesList, setRights, addRole, delRole, editdRole } from '@/api/roles'
import { removeRight, getRightsListTree } from '@/api/rights'
import { roleDescValidate, roleNameValidate } from '@/validate/validate'
export default {
  name: 'Roles',
  data () {
    return {
      roleList: [],
      setRightsDialogVisible: false,
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      rightsListTree: [], // 权限树的列表
      treeProps: {
        children: 'children',
        label: 'authName' // 树显示的字段
      },
      defaultCheckKeys: [],
      roleId: null,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, validator: roleNameValidate, trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, validator: roleDescValidate, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesLists()
  },
  methods: {
    async getRolesLists () {
      const { data: res } = await getRolesList()
      if (res.meta.status === 200) {
        this.roleList = res.data
      }
    },
    removeRightById (role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const params = {
          roleId: role.id,
          rightId
        }
        const { data: res } = await removeRight(params)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          role.children = JSON.parse(JSON.stringify(res.data))
        } else {
          this.$message.success(res.meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async openSetRights (role) {
      const { data: res } = await getRightsListTree()
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.rightsListTree = res.data
      }
      this.roleId = role.id
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defaultCheckKeys)
      this.setRightsDialogVisible = true
    },
    getLeafKeys (node, arr) {
      // 没有children
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClose () {
      this.defaultCheckKeys = []
    },
    async allotRights () {
      const keys = [
        ...this.$refs.rightTree.getCheckedKeys(),
        ...this.$refs.rightTree.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const params = {
        roleId: this.roleId,
        rids: idStr
      }
      const { data: res } = await setRights(params)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.setRightsDialogVisible = false
      } else {
        this.$message.success(res.meta.msg)
      }
    },
    addRole () {
      this.editRoleDialogVisible = true
    },
    saveAddRole () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await addRole(this.addForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.editRoleDialogVisible = false
            this.addForm = {
              roleName: '',
              roleDesc: ''
            }
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    addRoleDialogClose () {
      this.addRoleDialogVisible = false
      this.addForm = {
        roleName: '',
        roleDesc: ''
      }
    },
    editOpen (row) {
      this.editRoleDialogVisible = true
      this.roleId = row.id
      this.addForm = {
        roleName: row.roleName,
        roleDesc: row.roleDesc
      }
    },
    saveEditRole () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          const params = {
            roleId: this.roleId,
            data: this.addForm
          }
          const { data: res } = await editdRole(params)
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.getRolesLists()
            this.editRoleDialogVisible = false
            this.addForm = {
              roleName: '',
              roleDesc: ''
            }
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    async deleteRole (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await delRole(row.id)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.getRolesLists()
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>
<style lang="less" scoped>
  .el-tag{
    margin: 7px ;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
